package ch.exm.storm.query.join;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

public class Joiner {

	public static Collection<?> doJoin(Map<Class<?>, Collection<?>> workingSet) {
		// if there's just on type of objects in the working set there's actually nothing to join
		if (workingSet.size() == 1) return workingSet.values().iterator().next();
		
		Collection<JoinedObject> joins = null;
		for (Collection<?> objects : workingSet.values()) joins = addJoinSet(joins, objects);
		return joins;
	}
	
	private static Collection<JoinedObject> addJoinSet(Collection<JoinedObject> joins, Collection<?> objects) {
		Collection<JoinedObject> joined = new ArrayList<JoinedObject>();
		if (joins == null) for (Object object : objects) joined.add(new JoinedObject(object));
		else for (JoinedObject join : joins) for (Object object : objects) {
			JoinedObject clonedJoin = (JoinedObject)join.clone();
			clonedJoin.add(object);
			joined.add(clonedJoin);
		}
		return joined;
	}
}
